package com.macaline.framemarker.dataBase.framework.session;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库操作会话抽象类
 */
public abstract class AbstractDataBaseSession  implements IDataBaseSession {


    public static void main(String[] args) {

    }
    DataSource dataSource;

    /**
     * 设置操作的数据库
     * @param dataSource
     */
    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }

    /**
     * 获取连接数据库
     * @return
     */
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 执行sql语句
     * @param sql sql语句
     * @return
     * @throws SQLException
     */
    public Boolean execute(String sql) throws SQLException {
        System.out.println("execute..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Connection connection = getConnection();
        Statement statement = connection.createStatement();
        boolean result = statement.execute(sql);
        close(connection);
        return result;
    }

    /**
     * 执行sql语句
     * @param sql sql语句
     * @return
     * @throws SQLException
     */
    public Boolean executeByTransaction(String sql) throws SQLException {
        Connection connection = getConnection();
        startTransaction(connection);
        System.out.println("start transaction...");

        Statement statement = connection.createStatement();
        boolean result = statement.execute(sql);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("end transaction...");
        commit(connection);
        close(connection);
        return result;
    }


    /**
     * 关闭连接源
     * @param connection 连接源
     * @throws SQLException
     */
    public void close(Connection connection) throws SQLException {
        connection.close();
    }

    /**
     * 获取数据库源
     * @return
     */
    public DataSource getDataSource(){
        return dataSource;
    }

    public void startTransaction(Connection connection) throws SQLException {
        connection.setAutoCommit(false);
    }
    public void commit(Connection connection) throws SQLException {
        connection.commit();
    }

}
